package com.geovis.emergency.spd.controller.basic;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.geovis.common.core.api.Result;
import com.geovis.common.core.constant.SwaggerConstants;
import com.geovis.common.core.controller.BaseController;
import com.geovis.emergency.spd.biz.basic.service.IBasicShareDocService;
import com.geovis.emergency.spd.biz.basic.service.IBasicShareFolderService;
import com.geovis.emergency.spd.biz.system.wrapper.ForestNodeMerger;
import com.geovis.emergency.spd.entity.basic.entity.BasicShareDoc;
import com.geovis.emergency.spd.entity.basic.entity.BasicShareFolder;
import com.geovis.emergency.spd.entity.basic.pojo.dto.BasicShareDocUpdateDTO;
import com.geovis.emergency.spd.entity.basic.pojo.dto.UploadFileDTO;
import com.geovis.emergency.spd.entity.basic.pojo.dto.UploadFolderDTO;
import com.geovis.emergency.spd.entity.basic.pojo.enums.ShareDocFileTypeEnum;
import com.geovis.emergency.spd.entity.basic.pojo.vo.ShareDocTreeVO;
import com.geovis.emergency.spd.entity.pc.pojo.enums.StatusEnum;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.common.collect.Lists;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 基础模块-共享文档 前端控制器
 * </p>
*
* @author Lonsho
* @since 2022-07-12
*/
@RestController
@RequestMapping("/pc/basicShareDoc")
@RequiredArgsConstructor
@Api(value = "基础模块-共享文档接口", tags = "基础模块-共享文档接口")
@Slf4j
@Validated
public class BasicShareDocController extends BaseController<IBasicShareDocService> {

    private final IBasicShareFolderService shareFolderService;

    @PostMapping("/tree")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "文件树", notes = "")
    public Result<List<ShareDocTreeVO>> tree(@ApiParam(value = "演练id", name = "pcDrillId") @RequestParam(value = "pcDrillId", required = false) String pcDrillId) {
        List<ShareDocTreeVO> shareDocTreeVOList = Lists.newArrayList();
        // 共享目录
        List<BasicShareFolder> shareFolderList = shareFolderService.list(
                Wrappers.lambdaQuery(BasicShareFolder.class)
                        .eq(StrUtil.isNotBlank(pcDrillId),BasicShareFolder::getPcDrillId,pcDrillId)
                        .orderByAsc(BasicShareFolder::getName)
        );
        if (ObjectUtil.isNotEmpty(shareFolderList)){
            for (BasicShareFolder shareFolder : shareFolderList) {
                if (StatusEnum.FALSE.getCode().equals(shareFolder.getIsRoot())) {
                    ShareDocTreeVO shareDocTreeVO = BeanUtil.toBean(shareFolder, ShareDocTreeVO.class);
                    shareDocTreeVO.setParentId(shareFolder.getFolderId());
                    shareDocTreeVO.setType(ShareDocFileTypeEnum.FOLDER.getCode());
                    shareDocTreeVOList.add(shareDocTreeVO);
                }
            }
        }
        BasicShareFolder rootFolder = baseService.getOrCreateRootFolder(pcDrillId);
        List<String> folderIds = Lists.newArrayList(rootFolder.getId());
        if (CollectionUtil.isNotEmpty(shareFolderList)){
            folderIds.addAll(shareFolderList.stream().map(BasicShareFolder::getId).collect(Collectors.toList()));
        }
        List<BasicShareDoc> shareDocList = baseService.list(
                Wrappers.lambdaQuery(BasicShareDoc.class)
                        .eq(StrUtil.isNotBlank(pcDrillId),BasicShareDoc::getPcDrillId,pcDrillId)
                        .in(ObjectUtil.isNotEmpty(folderIds),BasicShareDoc::getFolderId,folderIds)
        );
        if (ObjectUtil.isNotEmpty(shareFolderList)){
            for (BasicShareDoc basicShareDoc : shareDocList) {
                ShareDocTreeVO shareDocTreeVO = BeanUtil.toBean(basicShareDoc,ShareDocTreeVO.class);
                shareDocTreeVO.setName(basicShareDoc.getFileName());
                shareDocTreeVO.setParentId(basicShareDoc.getFolderId());
                shareDocTreeVO.setType(ShareDocFileTypeEnum.FILE.getCode());
                shareDocTreeVOList.add(shareDocTreeVO);
            }
        }
        return Result.ok(ForestNodeMerger.merge(shareDocTreeVOList));

    }
    @PostMapping("/upload")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "上传文件到文件夹", notes = "上传文件到文件夹")
    public Result<ShareDocTreeVO> upload(UploadFileDTO uploadFileDTO) {
        return Result.ok(baseService.uploadFileInFolder(uploadFileDTO.getFile(),uploadFileDTO.getFolderId(),uploadFileDTO.getPcDrillId()));
    }
    @PostMapping("/uploadFolder")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "上传文件夹(批量上传并创建文件夹)", notes = "上传文件夹(批量上传并创建文件夹)")
    public Result<List<ShareDocTreeVO>> uploadFolder(UploadFolderDTO uploadFolderDTO) {
        return Result.ok(baseService.uploadFilesWithFolder(uploadFolderDTO.getFiles(), uploadFolderDTO.getFolderName(), uploadFolderDTO.getFolderId(),uploadFolderDTO.getPcDrillId()));
    }

    @PostMapping("/update")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = SwaggerConstants.UPDATE_VALUE, notes = SwaggerConstants.UPDATE_NOTES)
    public Result update(@Valid @RequestBody BasicShareDocUpdateDTO updateDTO) {
        BasicShareDoc basicShareDoc = baseService.getById(updateDTO.getId());
        String fileExt = basicShareDoc.getFileExt();
        BeanUtil.toBean(updateDTO, BasicShareDoc.class);
        if (StrUtil.isNotBlank(updateDTO.getFileName()) && StrUtil.isBlank(FileUtil.extName(updateDTO.getFileName()))){
            basicShareDoc.setFileName(updateDTO.getFileName()+"."+fileExt);
        }
        baseService.updateById(basicShareDoc);
        return Result.ok();
    }


    @ApiOperationSupport(order = 3)
    @ApiOperation(value = SwaggerConstants.GET_BY_ID_VALUE, notes = SwaggerConstants.GET_BY_ID_NOTES)
    @PostMapping("/getDetail/{id}")
    public Result<BasicShareDoc> getById(@PathVariable("id") String id) {
        return Result.ok(baseService.getById(id));
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation(value = SwaggerConstants.REMOVE_BY_ID_LIST_VALUE, notes = SwaggerConstants.REMOVE_BY_ID_LIST_NOTES)
    @ApiImplicitParams({@ApiImplicitParam(name = "idList", value = "删除id的list", required = true, dataType = "java.util.Set", paramType = "body")})
    @PostMapping("/removeByIdList")
    public Result removeByIdList(@NotNull(message = "删除的id集合不能为空") @RequestBody(required = false) Set<String> idList) {
        baseService.removeBatchByIds(idList);
        return Result.ok();
    }
}
